package com.mission.schedule.add603.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.my160920.FrendLyActivity;
import com.mission.schedule.my160920.RoundImageView;
import com.mission.schedule.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liwei on 2016/11/15.
 */

public class NewInformationAdapter extends RecyclerView.Adapter {

    private Context context;
    private List<Map<String,String>> nMap;
    private String userid;
    //0 新消息
    private int type = 0;

    public NewInformationAdapter(Context context,List<Map<String,String>> nMap,String uid,int type){
        this.context = context;
        this.nMap = nMap;
        this.userid = uid;
        this.type = type;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder myViewHolder = new MyViewHolder(
                LayoutInflater.from(context).inflate(R.layout.newinformation_cardview,parent,false));
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final MyViewHolder myViewHolder = (MyViewHolder) holder;
        if (position == 0){
            myViewHolder.kongbait.setVisibility(View.VISIBLE);
        }else if(position == nMap.size() - 1){
            myViewHolder.kongbait.setVisibility(View.GONE);
            myViewHolder.kongbaib.setVisibility(View.VISIBLE);
        }else {
            myViewHolder.kongbait.setVisibility(View.GONE);
            myViewHolder.kongbaib.setVisibility(View.GONE);
        }
        myViewHolder.num.setText(nMap.get(position).get("num")+"条");
        if (nMap.get(position).get("num").equals("-1")){
            myViewHolder.num.setVisibility(View.GONE);
        }
        if (nMap.get(position).get("newtype").equals("1")){
            myViewHolder.num.setVisibility(View.GONE);
        }
        if (nMap.get(position).get("remark").equals("")){
            String content = App.getDBcApplication().getCalenderContent(Integer.parseInt(nMap.get(position).get("calendarId")));
            String name = App.getDBcApplication().getCalenderName(Integer.parseInt(nMap.get(position).get("calendarId")));
            if (!content.equals("")){
                myViewHolder.newi_content.setVisibility(View.VISIBLE);
                myViewHolder.line.setVisibility(View.VISIBLE);
                myViewHolder.newi_content.setText(content);
            }else {
                myViewHolder.newi_content.setVisibility(View.GONE);
                myViewHolder.line.setVisibility(View.GONE);
            }
            myViewHolder.newi_content.setText("@"+name+" "+content);
        }else {
            myViewHolder.line.setVisibility(View.VISIBLE);
            myViewHolder.newi_content.setVisibility(View.VISIBLE);
            myViewHolder.newi_content.setText("@"+nMap.get(position).get("remark1")+" "+nMap.get(position).get("remark"));
        }

        myViewHolder.newi_name.setText("@"+nMap.get(position).get("U_NICK_NAME"));
        myViewHolder.newi_mess.setText(nMap.get(position).get("mess"));
        myViewHolder.newi_time.setText(nMap.get(position).get("opTime").replace("T"," ").substring(5,16));

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.img_null_smal)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.img_null_smal)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.img_null_smal)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
//                        .displayer(new RoundedBitmapDisplayer(20))  // 设置成圆角图片
                .build();

        String imageurl = URLConstants.HOST+"/TbDU_showImage.htm?imageName=" + nMap.get(position).get("U_PORTRAIT") + "&imageType=2&imageSizeType=3";
        ImageLoader.getInstance().displayImage(imageurl, myViewHolder.newi__icon, options);

        myViewHolder.cardview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    updateFrendsPostState(nMap.get(position).get("calendarId"));
                    App.getDBcApplication().updateReadState1(Integer.parseInt(nMap.get(position).get("calendarId")));
                    if (type == 1){
                        App.getDBcApplication().updateNewInforIsNew(nMap.get(position).get("calendarId"));
                    }
                    App.getDBcApplication().updateNewInforNewType(nMap.get(position).get("id"));
                    Intent intent1 = new Intent(context, FrendLyActivity.class);
                    intent1.putExtra("types", 4);
                    intent1.putExtra("calendarID", nMap.get(position).get("calendarId"));
                    intent1.putExtra("U_PORTRAIT", nMap.get(position).get("U_PORTRAIT"));
                    intent1.putExtra("remark", nMap.get(position).get("remark"));
                    intent1.putExtra("U_NICK_NAME", nMap.get(position).get("U_NICK_NAME"));
                    intent1.putExtra("schFriendID", nMap.get(position).get("uid"));
                    context.startActivity(intent1);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public int getItemCount() {
        return nMap.size();
    }


    class MyViewHolder extends RecyclerView.ViewHolder{

        View kongbait,kongbaib,line;
        CardView cardview;
        TextView num,newi_name,newi_time,newi_mess,newi_content;
        RoundImageView newi__icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            kongbait = (View)itemView.findViewById(R.id.kongbait);
            kongbaib = (View)itemView.findViewById(R.id.kongbaib);
            line = (View)itemView.findViewById(R.id.line);
            cardview = (CardView)itemView.findViewById(R.id.cardview);
            num = (TextView)itemView.findViewById(R.id.num);
            newi_name = (TextView)itemView.findViewById(R.id.newi_name);
            newi_time = (TextView)itemView.findViewById(R.id.newi_time);
            newi_mess = (TextView)itemView.findViewById(R.id.newi_mess);
            newi_content = (TextView)itemView.findViewById(R.id.newi_content);
            newi__icon = (RoundImageView)itemView.findViewById(R.id.newi__icon);
        }
    }

    /**
     * app日程同步下行修改好友信息和留言
     */
    public void updateFrendsPostState(final String cid) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST + "/appFrends_updateFrendsPostState.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                if (responseCode(result)) {
                                    //TODO  同步成功
                                } else {
//                                    updateFrendsPostState(cid);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userid);
                map.put("cId", cid);
                return map;
            }
        };
        stringRequest.setTag("findLyNewNum");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    public boolean responseCode(String response) throws JSONException {
        int status = 0;
        JSONObject jsonObject = new JSONObject(response);
        int msg = jsonObject.getInt("status");
        return status == msg;
    }
}
